const mongoose = require("mongoose")
const db = 'mongodb://127.0.0.1/doubanTest'
const glob = require('glob') //定制规则匹配
const {resolve} = require("path")

mongoose.Promise = global.Promise

exports.initSchema = () => {
    glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require)
}
exports.connect = () => {
    let maxConnectTimes = 0
    return new Promise((resolve,reject) => {
        if (process.env.NODE_ENV !== 'production') {
            mongoose.set('debug',true)
        }
        mongoose.connect(db,{ useNewUrlParser: true })
    
        mongoose.connection.on('disconnected', () => {
            maxConnectTimes++
            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error("数据库挂了吧")
            }
        })
        mongoose.connection.on('error', err => {
            console.log(err)
            reject()
        })
        mongoose.connection.once('open', () => {
            const Dog = mongoose.model('Dog',{name:String})
            const doga = new Dog({name:"aa"})
            doga.save().then(()=>{
                console.log("wang")
            })
            console.log('链接成功')
            resolve()
        })
    })
}